package cn.tedu._03vehicle.base.filters;

import cn.tedu._03vehicle.pojo.vo.UserLoginVo;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@WebFilter(filterName = "loginFilter",urlPatterns = {"/v1/vehicle/*"})
public class LoginFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(LoginFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.debug("创建过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        HttpSession session=request.getSession();
        UserLoginVo userLoginVo =(UserLoginVo) session.getAttribute("user");
        if(userLoginVo!=null)
            filterChain.doFilter(request, response);
        else
            response.sendRedirect("login.html");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        log.debug("过滤器销毁");
    }
}
